package com.probox.apiModules.controller.order;

import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.DeliverMethodEnum;
import com.probox.common.core.enums.OrderRechargeEnum;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.domain.customer.CustomerFund;
import com.probox.common.entity.domain.order.OrderInfoItem;
import com.probox.common.entity.domain.order.OrderInfoParent;
import com.probox.common.entity.domain.product.ProductInfo;
import com.probox.common.entity.service.customer.ICustomerFundService;
import com.probox.common.entity.service.order.IOrderInfoParentService;
import com.probox.common.entity.service.product.IProductInfoService;
import com.probox.common.entity.vo.proboxService.BalanceItemVo;
import com.probox.common.security.annotation.VerifyAuthorize;
import com.probox.common.entity.domain.order.vo.OrderMergeDetailVo;
import com.probox.common.entity.domain.order.vo.OrderMergeVo;
import com.probox.common.entity.domain.order.vo.OrderSettlementVo;
import com.probox.common.entity.domain.order.vo.PostSaleQuery;
import com.probox.common.entity.service.order.IOrderInfoItemService;
import com.probox.common.entity.service.order.IOrderInfoService;
import com.probox.common.entity.service.order.IOrderPostSaleService;
import com.probox.order.api.domain.*;
import com.probox.product.api.domain.LunWenVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Consumer;

@Api(value = "订单接口",tags = {"订单接口"})
@RestController
@RequestMapping("/order/openOrder")
public class OpenOrderInfoController extends BaseController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IOrderInfoItemService orderInfoItemService;

    @Autowired
    private IProductInfoService productInfoService;

    @Autowired
    private ICustomerFundService customerFundService;

    @Autowired
    private IOrderInfoParentService orderInfoParentService;



    /**
     * 下载单篇论文
     * @return
     */
    @VerifyAuthorize
    @ApiOperation("批量下载论文")
    @PostMapping(value = "/batchDownload")
    public AjaxResult download(@RequestBody OrderQuery orderQuery) throws Exception {
        if (orderQuery.getProductIds() == null || orderQuery.getProductIds().length==0){
            return AjaxResult.error("缺少论文ID集！");
        }
        Long[] productIds = orderQuery.getProductIds();
        List<String> fileList = new ArrayList<>();
        CustomerFund customerFund = customerFundService.getByCustomerId(SecurityUtils.getCustomerUid());
        if (customerFund == null){
            customerFund = new CustomerFund();
            customerFund.setCustomerUid(SecurityUtils.getCustomerUid());
            customerFund.setAllFans(0);
            customerFund.setAllBalance(0L);
            customerFund.setAllFansSecond(0);
            customerFund.setAllProfit(0L);
            customerFund.setAllScore(0L);
            customerFund.setAllWithdraw(0l);
            customerFund.setAllRedBag(0L);
            customerFund.setFreezeScore(0L);
            customerFund.setBalance(0L);
            customerFund.setRedBag(0L);
            customerFund.setAllRedBag(0L);
            customerFund.setFreezeRedBag(0L);
            customerFund.setCreateTime(new Date());
            customerFund.setPlatformUid(Constants.DEFAULT_PLATFORM_ID);
            customerFund.setUpdateTime(new Date());
            customerFund.setScore(0L);
            customerFund.setProfit(0L);
            customerFund.setFreezeProfit(0L);
            customerFundService.save(customerFund);
            return AjaxResult.error("您的积分不足，请先购买积分再下载！");
        }
        Long score = 0L;
        List<ProductInfo> productInfos = new ArrayList<>();
        for (Long productId: productIds) {
            ProductInfo productInfo = productInfoService.getById(productId);
            if (productInfo != null && productInfo.getDataStatus().equals("1")){
                if (productInfo.getJifen()>0){
                    LunWenVo lunWenVo = new LunWenVo();
                    lunWenVo.setCategoryUid(productInfo.getCategoryUid());
                    lunWenVo.setDownloadCount(productInfo.getDownloadCount());
                    lunWenVo.setJifen(productInfo.getJifen());
                    productInfo.setJifen(productInfoService.getDownloadJiFen(lunWenVo));

                    OrderQuery query = new OrderQuery();
                    query.setCustomerUid(SecurityUtils.getCustomerUid());
                    //query.setOrderType("good");
                    query.setProUid(productId);
                    //如果已经购买了，直接下载
                    if(orderInfoItemService.selectLuwenOrderListCount(query)==0){
                        productInfo.setOrderType("good");
                        productInfos.add(productInfo);
                        score += productInfo.getJifen().longValue();
                    }else{
                        fileList.add(productInfo.getDownloadFile());
                    }
                }
            }else{
                return AjaxResult.error(productInfo.getProductName()+"已下架不能下载！");
            }
        }
        if ((customerFund.getScore()- customerFund.getFreezeScore())<score){
            return AjaxResult.error("您的积分不足，请先购买积分再下载！");
        }

        for (ProductInfo p:productInfos ) {
            OrderSettlementVo vo = new OrderSettlementVo();
            vo.setProductInfo(p);
            vo.setShopAmount(0L);
            vo.setScoreAmount(p.getJifen().longValue());
            vo.setPayMethod("wechat");
            vo.setBatch(true);
            vo.setIsRecharge(OrderRechargeEnum.good.getKey());
            orderInfoService.createOrder(vo);
            fileList.add(httpToHttps(p.getDownloadFile()));
        }
        return AjaxResult.success(fileList);
    }

    /**
     * 下载单篇论文
     * @return
     */
    @VerifyAuthorize
    @ApiOperation("下载论文")
    @PostMapping(value = "/download/{productId}")
    public AjaxResult download(@PathVariable("productId") Long productId) throws Exception {
        ProductInfo productInfo = productInfoService.getById(productId);
        if (productInfo != null && productInfo.getDataStatus().equals("1")){

            if (productInfo.getJifen()>0){
                LunWenVo lunWenVo = new LunWenVo();
                lunWenVo.setCategoryUid(productInfo.getCategoryUid());
                lunWenVo.setDownloadCount(productInfo.getDownloadCount());
                lunWenVo.setJifen(productInfo.getJifen());
                productInfo.setJifen(productInfoService.getDownloadJiFen(lunWenVo));
                OrderQuery query = new OrderQuery();
                query.setCustomerUid(SecurityUtils.getCustomerUid());
                //query.setOrderType("good");
                query.setProUid(productId);
                //如果已经购买了，直接下载
                if(orderInfoItemService.selectLuwenOrderListCount(query)>0){
                    return AjaxResult.success("操作成功",httpToHttps(productInfo.getDownloadFile()));
                }else{
                    CustomerFund customerFund = customerFundService.getByCustomerId(SecurityUtils.getCustomerUid());
                    if (customerFund == null){
                        customerFund = new CustomerFund();
                        customerFund.setCustomerUid(SecurityUtils.getCustomerUid());
                        customerFund.setAllFans(0);
                        customerFund.setAllBalance(0L);
                        customerFund.setAllFansSecond(0);
                        customerFund.setAllProfit(0L);
                        customerFund.setAllScore(0L);
                        customerFund.setAllWithdraw(0l);
                        customerFund.setAllRedBag(0L);
                        customerFund.setFreezeScore(0L);
                        customerFund.setBalance(0L);
                        customerFund.setRedBag(0L);
                        customerFund.setAllRedBag(0L);
                        customerFund.setFreezeRedBag(0L);
                        customerFund.setCreateTime(new Date());
                        customerFund.setPlatformUid(Constants.DEFAULT_PLATFORM_ID);
                        customerFund.setUpdateTime(new Date());
                        customerFund.setScore(0L);
                        customerFund.setProfit(0L);
                        customerFund.setFreezeProfit(0L);
                        customerFundService.save(customerFund);
                        return AjaxResult.error("您的积分不足，请先购买积分再下载！");
                    }
                    if ((customerFund.getScore()- customerFund.getFreezeScore())<productInfo.getJifen()){
                        return AjaxResult.error("您的积分不足，请先购买积分再下载！");
                    }
                    productInfo.setOrderType("good");
                    OrderSettlementVo vo = new OrderSettlementVo();
                    vo.setProductInfo(productInfo);
                    vo.setShopAmount(0L);
                    vo.setScoreAmount(productInfo.getJifen().longValue());
                    vo.setPayMethod("wechat");
                    vo.setIsRecharge(OrderRechargeEnum.good.getKey());
                    orderInfoService.createOrder(vo);
                }
            }
            //如果不需要积分，直接下载
            return AjaxResult.success("操作成功",httpToHttps(productInfo.getDownloadFile()));
        }
        return AjaxResult.error("没有找到论文资料");
    }

    private String httpToHttps(String file){
        String rst = "https:";
        if (StringUtils.isNotEmpty(file) && file.startsWith("http:")){
            rst += file.substring(5);
        }else {
            rst = file;
        }
        return rst;
    }


    /**
     * 买断单篇论文
     * @return
     */
    @VerifyAuthorize
    @ApiOperation("买断论文")
    @PostMapping(value = "/maiduan/{productId}")
    public AjaxResult maiduan(@PathVariable("productId") Long productId) throws Exception {

        ProductInfo productInfo = productInfoService.getById(productId);
        if (productInfo != null && productInfo.getDataStatus().equals("1")){
            if (productInfo.getCostPrice()>0){
                OrderQuery query = new OrderQuery();
                query.setCustomerUid(SecurityUtils.getCustomerUid());
                query.setOrderType("maiduan");
                query.setProUid(productId);
                //如果已经购买了，直接下载
                if(orderInfoItemService.selectLuwenOrderListCount(query)>0){
                    return AjaxResult.success("买断成功",httpToHttps(productInfo.getDownloadFile()));
                }else{
                    CustomerFund customerFund = customerFundService.getByCustomerId(SecurityUtils.getCustomerUid());
                    if (customerFund == null){
                        customerFund = new CustomerFund();
                        customerFund.setCustomerUid(SecurityUtils.getCustomerUid());
                        customerFund.setAllFans(0);
                        customerFund.setAllBalance(0L);
                        customerFund.setAllFansSecond(0);
                        customerFund.setAllProfit(0L);
                        customerFund.setAllScore(0L);
                        customerFund.setAllWithdraw(0l);
                        customerFund.setAllRedBag(0L);
                        customerFund.setFreezeScore(0L);
                        customerFund.setBalance(0L);
                        customerFund.setRedBag(0L);
                        customerFund.setAllRedBag(0L);
                        customerFund.setFreezeRedBag(0L);
                        customerFund.setCreateTime(new Date());
                        customerFund.setPlatformUid(Constants.DEFAULT_PLATFORM_ID);
                        customerFund.setUpdateTime(new Date());
                        customerFund.setScore(0L);
                        customerFund.setProfit(0L);
                        customerFund.setFreezeProfit(0L);
                        customerFundService.save(customerFund);
                        return AjaxResult.error("您的积分不足，请先购买积分再买断！");
                    }
                    if ((customerFund.getScore()- customerFund.getFreezeScore())<productInfo.getCostPrice()){
                        return AjaxResult.error("您的积分不足，请先购买积分再买断！");
                    }
                    productInfo.setOrderType("maiduan");
                    OrderSettlementVo vo = new OrderSettlementVo();
                    vo.setProductInfo(productInfo);
                    vo.setShopAmount(0L);
                    vo.setScoreAmount(productInfo.getCostPrice().longValue());
                    vo.setPayMethod("wechat");
                    vo.setIsRecharge(OrderRechargeEnum.good.getKey());
                    orderInfoService.createOrder(vo);
                }
            }
            //如果不需要积分，直接下载
            return AjaxResult.success("买断成功",httpToHttps(productInfo.getDownloadFile()));
        }
        return AjaxResult.error("没有找到论文资料");
    }

    /**
     * 我的订单列表
      */
    @VerifyAuthorize
    @ApiOperation("论文下载列表/买断列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = OrderInfoVo.class),
    })
    @GetMapping(value = "/mine")
    public AjaxResult myOrder(OrderQuery query){
        query.setCustomerUid(SecurityUtils.getCustomerUid());
        query.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        if (StringUtils.isEmpty(query.getOrderType())){
            query.setOrderType("good");
        }
        if (StringUtils.isNotEmpty(query.getEndDate())){
            if (query.getEndDate().indexOf(":")<0){
                query.setEndDate(query.getEndDate()+" 23:59:59");
            }
        }
        startPage();
        List<OrderInfoItem> items = orderInfoItemService.selectLuwenOrderList(query);
        return AjaxResult.successs(items,orderInfoItemService.selectLuwenOrderListCount(query));
    }



    /**
     * 订单详情
     */
    @ApiOperation("订单详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = OrderInfoVo.class),
    })
    @GetMapping(value = "/detail/{orderUid}")
    public AjaxResult orderDetail(@PathVariable("orderUid") Long orderUid){
        return AjaxResult.success(orderInfoService.selectOrderInfoById(orderUid));
    }


    @ApiOperation("查看订单是否已完成支付")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = OrderInfoVo.class),
    })
    @VerifyAuthorize
    @GetMapping(value = "/payStatus/{orderNo}")
    public AjaxResult payStatus(@PathVariable("orderNo") String orderNo){
        OrderInfoParent parent = orderInfoParentService.getOrderInfo(orderNo);
        if (parent == null){
            return AjaxResult.error("没有找到订单信息");
        }
        Map rst = new HashMap<>();
        if (parent.getPayStatus().equals("1") && parent.getCustomerId().longValue()==SecurityUtils.getCustomerUid()){
            rst.put("payStatus","1");
        }else{
            rst.put("payStatus","0");
        }
        return AjaxResult.success(rst);
    }


    /**
     * 购买会员

    @VerifyAuthorize
    @ApiOperation("购买会员")
    @PostMapping(value = "/buyVip")
    public AjaxResult buyVip(@RequestBody OrderSettlementVo settle){
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        settle.setCustomerName(SecurityUtils.getCustomerUserName());
        settle.setPhone(SecurityUtils.getCustomerPhone());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        settle.setPlatSource(SecurityUtils.getCustomerSourcePort());
        return AjaxResult.success(orderInfoService.buyVip(settle));
    }*/

    /**
     * VIP充值订单
     */
    @VerifyAuthorize
    @ApiOperation("充值")
    @PostMapping(value = "/toRecharge")
    public AjaxResult toRecharge(@RequestBody OrderSettlementVo settle){
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        settle.setCustomerName(SecurityUtils.getCustomerUserName());
        settle.setPhone(SecurityUtils.getCustomerPhone());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        settle.setPlatSource(SecurityUtils.getCustomerSourcePort());
        settle.setOrderType("vip");
        return AjaxResult.success(orderInfoService.toRecharge(settle));
    }


    /**
     * 临时充值订单
     */
    @VerifyAuthorize
    @ApiOperation("临时充值兑换积分")
    @PostMapping(value = "/rechargeMoney")
    public AjaxResult rechargeMoney(@RequestBody OrderSettlementVo settle){
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        settle.setCustomerName(SecurityUtils.getCustomerUserName());
        settle.setPhone(SecurityUtils.getCustomerPhone());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        settle.setPlatSource(SecurityUtils.getCustomerSourcePort());
        settle.setOrderType("scan");
        if (settle.getScore() ==null || settle.getScore()<=0){
            return AjaxResult.error("缺少需要购买的积分数量!");
        }
        return AjaxResult.success(orderInfoService.rechargeMoney(settle));
    }


}
